package com.jcoinexchange.web.handler;

import com.jcoinexchange.web.entity.BasicResponse;
import com.jcoinexchange.web.entity.ResponseBaseCode;
import com.jcoinexchange.web.exception.ExternalException;
import com.jcoinexchange.web.exception.InternalException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;

import java.util.List;

/**
 * 错误拦截
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    // 拦截API异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<BasicResponse<?>> handleException(Exception e) {
        BasicResponse<?> response;
        if (e instanceof InternalException e0) {
            response = BasicResponse.error(e0.getCode(), e0.getErrorMsg());
        } else if (e instanceof ExternalException e1) {
            response = BasicResponse.error(e1.getCode(), e1.getErrorMsg());

        }else if(e instanceof BindException e2){

            List<FieldError> fieldErrors = e2.getBindingResult().getFieldErrors();
            StringBuilder errorMessage = new StringBuilder();
            for (FieldError fieldError : fieldErrors) {
                errorMessage.append(fieldError.getDefaultMessage()).append("; ");
            }
            BasicResponse<?> errorResp = BasicResponse.error(ResponseBaseCode.ERROR_PARAM_INVALID, errorMessage.toString());
            return new ResponseEntity<>(errorResp, HttpStatus.BAD_REQUEST);
        } else {
            response =  BasicResponse.error(ResponseBaseCode.ERROR_SYSTEM_EXCEPTION);
        }
        return ResponseEntity.ok(response);
    }

}
